package com.ruoyi.web.controller.master;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.ActivityEnum;
import com.ruoyi.common.utils.ExceptionFinalMessage;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.master.domain.Club;
import com.ruoyi.master.domain.PmActivity;
import com.ruoyi.master.service.IClubService;
import com.ruoyi.master.service.IPmActivityService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;

@RestController
@RequestMapping("/master/myActivity" )
public class MyActivityController extends BaseController {

    @Autowired
    private IPmActivityService iPmActivityService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IClubService clubService;

    /**
     * 查询活动主列表
     */
    @PreAuthorize("@ss.hasPermi('master:myActivity:list')")
    @GetMapping("/list")
    public TableDataInfo list(PmActivity pmActivity) {
        startPage();

        Club club = getLoginClub();
        LambdaQueryWrapper<PmActivity> activityLambdaQueryWrapper = Wrappers.lambdaQuery();
        activityLambdaQueryWrapper.eq(PmActivity::getClubId, club.getId())
                .like(StringUtils.isNotBlank(pmActivity.getTitle()), PmActivity::getTitle, pmActivity.getTitle())
                .le(pmActivity.getBegindate() != null, PmActivity::getEnddate, pmActivity.getBegindate())
                .ge(pmActivity.getEnddate() != null, PmActivity::getBegindate, pmActivity.getEnddate())
                .eq(pmActivity.getState() != null, PmActivity::getState, pmActivity.getState())
                .eq(pmActivity.getPlace() != null, PmActivity::getPlace, pmActivity.getPlace());
        return getDataTable(iPmActivityService.list(activityLambdaQueryWrapper));
    }

    /**
     * 获取活动主详细信息
     */
    @PreAuthorize("@ss.hasPermi('master:myActivity:query')" )
    @GetMapping(value = "/{id}" )
    public AjaxResult getInfo(@PathVariable("id" ) Long id) {
		PmActivity activity = iPmActivityService.getById(id);
		if (activity != null) {
			if(activity.getState() == 20) {
				return AjaxResult.error(ExceptionFinalMessage.STATUS_IS_APPROVAL_SUCCESS);

			} else {
				return AjaxResult.success(activity);
			}
		}
		return AjaxResult.error(ExceptionFinalMessage.DATA_IS_ERROR);

	}

    /**
     * 新增活动主
     */
    @PreAuthorize("@ss.hasPermi('master:myActivity:add')" )
    @Log(title = "活动主" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PmActivity pmActivity) {
        Club club = getLoginClub();
        pmActivity.setClubId(club.getId());
        pmActivity.setState(ActivityEnum.ActivityStateEnum.INIT.getValue());
        return toAjax(iPmActivityService.save(pmActivity) ? 1 : 0);
    }

    /**
     * 修改活动主
     */
    @PreAuthorize("@ss.hasPermi('master:myActivity:edit')" )
    @Log(title = "活动主" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PmActivity pmActivity) {
        return toAjax(iPmActivityService.updateById(pmActivity) ? 1 : 0);
    }

    /**
     * 删除活动主
     */
    @PreAuthorize("@ss.hasPermi('master:myActivity:remove')" )
    @Log(title = "活动主" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}" )
    public AjaxResult remove(@PathVariable Long[] ids) {

		Integer status = iPmActivityService.queryApprovalStatus(ids[0]);
		if (status != null && status != 0) {
			return AjaxResult.error(ExceptionFinalMessage.STATUS_IS_NOT_ALLOW_DELETED);
		}

        return toAjax(iPmActivityService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /**
     * 提交审批
     */
    @PreAuthorize("@ss.hasPermi('master:myActivity:approval')" )
    @Log(title = "活动主" , businessType = BusinessType.DELETE)
    @GetMapping("/approval/{ids}" )
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult approval(@PathVariable Long[] ids) {
        try {
			Integer status = iPmActivityService.queryApprovalStatus(ids[0]);
			if (status != null && status == 20) {
				return AjaxResult.error(ExceptionFinalMessage.STATUS_IS_APPROVAL_SUCCESS);
			}

            LambdaUpdateWrapper<PmActivity> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.set(PmActivity::getState, ActivityEnum.ActivityStateEnum.WAIT.getValue())
                    .in(PmActivity::getId, ids);
            iPmActivityService.update(updateWrapper);
            return AjaxResult.success();
        } catch(Exception e) {
            logger.error(e.getMessage(), e);
            return AjaxResult.error("提交审批失败，请核查后重新提交");
        }
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("imgUrl", avatar);
            // 更新缓存用户头像
            return ajax;
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    public Club getLoginClub() {
        SysUser user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        LambdaQueryWrapper<Club> clubLambdaQueryWrapper = Wrappers.lambdaQuery();
        return clubService.getOne(clubLambdaQueryWrapper.eq(Club::getUserId, user.getUserId()));
    }
}
